<template>
  <div>
    <!-- 操作按钮 -->
    <el-row :gutter="20" class="gl_my_15">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="openAddHotel()">添加酒店</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" class="gl_table_noBorder" :border="false" stripe size="mini">
      <el-table-column prop="imageUrl" label="酒店图片" align="center">
        <template slot-scope="{row}">
          <img class="hotelPhoto" :src="getStaticFileUrl(row.imageUrl)" alt="" @error="errorPhoto" @mouseenter="showImg(...arguments, row.imagePath)" @mouseleave="hideImg(row.imagePath)">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="酒店名称" align="center" />
      <el-table-column prop="address" label="酒店地址" align="center" />
      <el-table-column prop="roomType" label="房型" align="center" />
      <el-table-column prop="price" label="价格" align="center">
        <template slot-scope="{row}">
          <span>{{ formatMoney(row.price) }}</span>
          <span>元</span>
        </template>
      </el-table-column>
      <el-table-column label="入住时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="离店时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.endTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="餐食" align="center">
        <template slot-scope="{row}">
          <span>{{ row.includeBreakfast === true ? '早餐' : '' }}</span>
          <span>{{ row.includeLunch === false ? '' : (row.includeBreakfast === true ? ',午餐' :'午餐') }}</span>
          <span>{{ row.includeDinner === false ? '' : ( row.includeBreakfast === true || row.includeLunch === true ? ',晚餐' :'晚餐') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="roomCount" label="房间数量" align="center" />
      <el-table-column prop="comment" label="备注" align="center" />
      <el-table-column prop="operating" label="操作" align="center" width="200">
        <template slot-scope="{row,$index}">
          <el-button type="text" size="mini" @click="openEdit(row,$index)">编辑</el-button>
          <el-button type="text" size="mini" @click="deleteItem(row,$index)">
            <span class="gl_color_error">删除</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 子组件添加编辑 -->
    <test-form ref="testForm" @pushTabelData="getTabelDate" @editTabelData="updataTabelDate" />
  </div>
</template>

<script>
import testForm from './editHotel';
import defaultHotelImg from '@/assets/images/face_default.png';

import {
  api_GET_TrainTrainningHotel, // 获取培训酒店列表
  api_POST_TrainTrainningHotel, // 新建培训酒店
  api_PUT_TrainTrainningHotelId, // 更新培训酒店
  api_DELETE_TrainTrainningHotelId, // 删除培训酒店
  api_GET_TrainTrainningHotelId // 获取培训酒店
} from '@/extend/api/trainswaggerApi/app.js';

import { Api_GET_TrainTrainningHotelQO } from '@/lib/form/train/swaggerForm.js';
export default {
  components: {
    testForm
  },
  data () {
    return {
      memberFeeName: '',
      qo: new Api_GET_TrainTrainningHotelQO(),
      tableData: [],
      loading: false,
      totalPage: 0,
      defaultHotelImg: defaultHotelImg
    };
  },
  created() {
    this.init();
    this.getPageList();
  },
  methods: {
    // 初始化
    init() {
      this.TrainningId = this.$route.params.id;
    },
    // 获取数据
    getPageList() {
      // 手动转换0为null
      this.qo.MinRoomCount = null;
      this.qo.MinPrice = null;
      this.qo.MaxPrice = null;
      this.qo.TrainningId = this.$route.params.id;
      this.loading = true;
      api_GET_TrainTrainningHotel(this.qo).then(
        res => {
          this.loading = false;
          if (res.items) {
            this.tableData = res.items || [];
          }
        }
      )
        .catch(
          error => {
            this.loading = false;
            this.$message({
              message: `列表获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 新增
    openAddHotel() {
      this.$refs.testForm.open();
    },
    // 编辑
    openEdit(row, index) {
      api_GET_TrainTrainningHotelId(row.id).then(
        res => {
          this.vo = res;
          this.$refs.testForm.open(row);
        }
      ).catch(
        error => {
          this.$message({
            message: `获取酒店信息失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
        }
      );
    },
    // 删除
    deleteItem(row, index) {
      this.$confirm(`您确定要删除${row.name}信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            api_DELETE_TrainTrainningHotelId(row.id).then(
              res => {
                this.$message({
                  message: `删除成功`,
                  type: 'success',
                  showClose: true
                });
                this.getPageList();
              }
            ).catch(
              error => {
                this.$message({
                  message: `删除失败 ${error.error.message}`,
                  type: 'error',
                  showClose: true
                });
              }
            );
          }
        );
    },
    // 添加新信息
    getTabelDate(data) {
      console.log('gettabledata', data);
      data.trainningId = this.TrainningId;
      api_POST_TrainTrainningHotel(data).then(
        res => {
          this.$message({
            message: `添加成功`,
            type: 'success',
            showClose: true
          });
          this.$refs.testForm.close();
          this.getPageList();
        }
      ).catch(
        error => {
          this.$message({
            message: `添加失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
          this.$refs.testForm.close();
        }
      );
    },
    // 修改信息
    updataTabelDate(data) {
      console.log('updateData', data);
      api_PUT_TrainTrainningHotelId(data.id, data).then(
        res => {
          this.$message({
            message: `更新成功`,
            type: 'success',
            showClose: true
          });
          this.$refs.testForm.close();
          this.getPageList();
        }
      ).catch(
        error => {
          this.$message({
            message: `更新失败 ${error.error.message}`,
            type: 'error',
            showClose: true
          });
          this.$refs.testForm.close();
        }
      );
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultHotelImg;
    },
    showImg(event, img) {
      const _this = this;
      _this.bigImg = img;
      const _img = event.target; // 这里就是获取到的dom元素
      const _position = _img.getBoundingClientRect();
      this.timeOut = setTimeout(() => {
        _this.isShowImg = true;
        this.$set(this.position, 'left', _position.left + 60 + 'px');
        this.$set(this.position, 'top', _position.top + 'px');
      }, 300);
    },
    hideImg(img) {
      const _this = this;
      clearTimeout(this.timeOut);
      _this.isShowImg = false;
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.hotelPhoto{
  width: 48px;
  height: 36px;
  vertical-align: middle;
}
.hotelBigPhoto{
  width: 310px;
  height: 280px;
  position: absolute;
  z-index: 10;
  left: 70px;
}
</style>
